﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ColdSun.Commons;
using ColdSun.Commons.Configs;
using ColdSun.Commons.Entities;
using ColdSun.Services;
using System.IO;
using ColdSun.Framework;

namespace ColdSun.BankManagements
{
    public partial class CtrlUpdateAddress : UserControl
    {
        private FrmProgressBar frmProgressBar = new FrmProgressBar(); 
        private string infoFile;
        private string wordTemplateFile;

        public CtrlUpdateAddress()
        {
            InitializeComponent();
        }

        private void CtrlUpdateAddress_Load(object sender, EventArgs e)
        {
            txtOriginalFile.Text = Utilities.GetFullFileName(CommonConfigs.UpdateAddressOriginalExcelFile);
            txtColumnNames.Text = CommonConfigs.UpdateAddressUpdateColumns;
            //txtOriginalFile.Text = "TO 10 P11 P PHU THANH,VINH THANH-NHA TRANG,KH,P.TAN LOC, Q.THOT NOT, TPCT";
            txtExportWordFile.Text = CommonConfigs.UpdateAddressExportFile;
            txtExportFolder.Text = Utilities.GetFullFileName(CommonConfigs.UpdateAddressExportFolder);
            txtHeaderRowIndex.Text = CommonConfigs.UpdateAddressHeaderRowIndex;
            this.infoFile = Utilities.GetFullFileName(CommonConfigs.UpdateAddressInfoFile);
        }

        private void ReplaceParamsInDoc()
        {
            Replacement replace = new Replacement();
            replace.SheetName = "Sheet1";
            replace.ReplaceTextDetails = new List<ReplaceTextDetail>();
            replace.ReplaceTextDetails.Add(new ReplaceTextDetail());
            replace.ReplaceTextDetails[0].SourceText = "Source";
            replace.ReplaceTextDetails[0].DestText = "Dest";
            replace.ReplaceTextDetails[0].ExcludedTexts = "exclude";
            replace.ReplaceTextDetails[0].Type = "End";

            string result = XmlUtility.SerializeObject<Replacement>(replace);
            MessageBox.Show(result);
        }

        private void btnOriginalFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog.Filter = "Excel Files (.xlsx)|*.xlsx|Excel Files (.xls)|*.xls|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtOriginalFile.Text = openFileDialog.FileName;
            }
        }

        private void btnExportFolder_Click(object sender, EventArgs e)
        {
            ReplaceParamsInDoc();
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                txtExportFolder.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(UpdateAddress(txtOriginalFile.Text));
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundWorker_DoWork);
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundReplaceWorker_RunWorkerCompleted);

            // Kick off the Async thread
            backgroundWorker.RunWorkerAsync();

            // Lock up the UI with this modal progress form.
            frmProgressBar.ShowDialog();
        }

        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Logger.Info(string.Format("----- BEGIN TO PROCESS INSURANCE -----"));

            try
            {
                Replacement replacementInfos = GetReplacementInfo(this.infoFile);
                if (replacementInfos == null)
                {
                    Logger.Info(string.Format("Can not get replacement information"));
                    return;
                }

                int headerRowIndex = Convert.ToInt32(txtHeaderRowIndex.Text);
                UpdateAddressService service = new UpdateAddressService();
                string result = service.UpdateAddress(
                    txtOriginalFile.Text, replacementInfos, this.txtColumnNames.Text.Trim(),
                    headerRowIndex, cbSaveAs.Checked, txtExportWordFile.Text,
                    txtExportFolder.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
            finally
            {
                Logger.Info(string.Format("----- END TO PROCESS INSURANCE -----"));
            }
        }

        private void BackgroundReplaceWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (frmProgressBar != null)
            {
                frmProgressBar.Close();
            }
        }

        private Replacement GetReplacementInfo(string file)
        {
            try
            {
                TextReader tr = new StreamReader(file);
                string xmlString = tr.ReadToEnd();
                return XmlUtility.DeserializeObject<Replacement>(xmlString);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            return null;
        }
    }
}
